package services;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import models.TimeUser;
import models.Workday;
import models.Workday.WorkdayType;
import time.Interval;

public class UserService {

	public static Set<TimeUser> allPresent(int offset, int limit,
			Interval interval) {
		return allByWorkType(WorkdayType.NORMAL, offset, limit, interval);
	}

	public static Set<TimeUser> allAbsent(int offset, int limit,
			Interval interval) {
		return allByWorkType(WorkdayType.ABSENT, offset, limit, interval);
	}

	public static Set<TimeUser> allSick(int offset, int limit, Interval interval) {
		return allByWorkType(WorkdayType.SICK, offset, limit, interval);
	}

	public static Set<TimeUser> allHoliday(int offset, int limit,
			Interval interval) {
		return allByWorkType(WorkdayType.HOLIDAY, offset, limit, interval);
	}

	public static Set<TimeUser> all(int offset, int limit, Interval interval) {

		List<Workday> wdays = Workday.find(
				"FROM Workday w WHERE w.startTime > ?1 AND w.endTime < ?2",
				interval.start, interval.end).fetch();

		Set<TimeUser> users = new HashSet<TimeUser>();

		for (Iterator iterator = wdays.iterator(); iterator.hasNext();) {
			Workday workday = (Workday) iterator.next();
			users.add(workday.owner);
		}

		return users;
	}

	public static Set<TimeUser> allByWorkType(WorkdayType workType, int offset,
			int limit, Interval interval) {

		List<Workday> wdays = Workday
				.find("FROM Workday w WHERE w.startTime > ?1 AND w.endTime < ?2 AND w.dayType = ?3",
						interval.start, interval.end, workType).fetch();

		Set<TimeUser> users = new HashSet<TimeUser>();

		for (Iterator iterator = wdays.iterator(); iterator.hasNext();) {
			Workday workday = (Workday) iterator.next();
			users.add(workday.owner);
		}

		return users;
	}

}
